package com.boyicloud.exchangeserver.security

import com.boyicloud.exchangeserver.common.TokenManager
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter
import javax.servlet.FilterChain
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

class TokenAuthFilter(authenticationManager: AuthenticationManager, private val tokenManager: TokenManager) :
    BasicAuthenticationFilter(authenticationManager) {


    override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {
        val authentication = getAuthentication(request)

        if (authentication == null) {
            throw AuthenticationCredentialsNotFoundException("token is empty or bad")
        } else {
            SecurityContextHolder.getContext().authentication = authentication
            chain.doFilter(request, response)
        }
    }


    private fun getAuthentication(request: HttpServletRequest): Authentication? {
        val token = request.getHeader("token")
        if (token.isNotEmpty()) {
            val username = tokenManager.getUserFromToken(token)
            return UsernamePasswordAuthenticationToken(username, token, listOf())
        }
        return null
    }
}